<template>
  <div class="shopcar">
    <van-nav-bar
      title="购物袋"
      :right-text="isshow ? '' : isEdit ? '完成' : '编辑'"
      fixed
      @click-right="compile"
    ></van-nav-bar>
    <div class="shopcar-body">
      <van-empty description="你目前还没有登录喔，快去登录吧" v-if="flag">
        <van-button round type="danger" class="bottom-button" @click="goLOgin"
          >去登录</van-button
        >
      </van-empty>
      <div v-else>
        <van-empty description="购物袋没有东西啦，快到菜单看看吧" v-if="isshow">
          <van-button
            round
            type="danger"
            class="bottom-button"
            @click="gocaidan"
            >去菜单</van-button
          >
        </van-empty>
        <van-swipe-cell
          :before-close="beforeClose"
          v-for="(value, index) in resultdata"
          :key="index"
        >
          <van-cell-group>
            <div class="cell-box">
              <div class="cheak">
                <van-checkbox
                  v-model="value.ischeak"
                  @change="checka(value)"
                ></van-checkbox>
              </div>
              <div class="cell-img" @click="godatail(value)">
                <img class="auto-img" :src="value.small_img" alt />
              </div>
              <div class="cell-info">
                <div class="info-top">
                  {{ value.name }}
                  <span>{{ value.rule }}</span>
                </div>
                <div class="info-center">{{ value.enname }}</div>
                <div class="info-bottom">
                  <div class="price">￥{{ value.price }}</div>
                  <div>
                    <van-stepper
                      v-model="value.count"
                      theme="round"
                      @change="changes(value)"
                      button-size="22"
                      disable-input
                    />
                  </div>
                </div>
              </div>
            </div>
          </van-cell-group>

          <template #right>
            <van-button
              square
              color="#0b37be"
              @click="letthis(value)"
              text="删除"
            />
          </template>
        </van-swipe-cell>
      </div>
    </div>
    <div class="shopca-bottom" v-if="ishide">
      <van-submit-bar
        :price="price"
        :button-text="isEdit ? '删除' : '提交订单'"
        @submit="onSubmit"
      >
        <van-checkbox v-model="isAll" @click="allCheck">全选</van-checkbox>
      </van-submit-bar>
    </div>
  </div>
</template>

<script>
import { getToken } from '@/utils/storage'
import '../../assets/less/Shoucar.less'
import {
  findAllShopcartAPI,
  removeShopcartAPI,
  modifyShopcartCountAPI
} from '@/api/user'
import { Dialog } from 'vant'
export default {
  data () {
    return {
      isshow: true,
      ishide: true,
      isEdit: false,
      isAll: false,
      resultdata: [],
      price: 0,
      sid: [],
      flag: false
    }
  },
  created () {
    this.eachshop()
    if (this.resultdata.length) {
      this.isshow = false
      this.ishide = true
    } else {
      this.isshow = true
      this.ishide = false
    }
  },
  updated () {
    if (this.resultdata.length) {
      this.isshow = false
      this.ishide = true
    } else {
      this.isshow = true
      this.ishide = false
    }
  },
  methods: {
    // 点击图片去详情页
    godatail (value) {
      this.$router.push({ name: 'Detail', query: { pid: value.pid } })
    },
    // 编辑
    compile () {
      this.isEdit = !this.isEdit
    },
    // 获取点击的删除的id
    letthis (value) {
      this.sid = []
      this.sid.push(value.sid)
      this.sid = JSON.stringify(this.sid)
    },
    // 确定删除
    beforeClose ({ position, instance }) {
      console.log(position, instance)
      switch (position) {
        case 'left':
        case 'cell':
        case 'outside':
          instance.close()
          break
        case 'right':
          Dialog.confirm({
            message: '确定删除吗？'
          })
            .then(() => {
              instance.close()
              this.remove()
              //  确定删除
            })
            .catch(ree => {
              // 取消删除
            })
          break
      }
    },
    // 提交订单或者删除商品
    onSubmit () {
      // 删除
      this.sid = []
      this.resultdata.forEach(v => {
        if (v.ischeak) {
          this.sid.push(v.sid)
        }
      })
      if (this.sid.length === 0) {
        Dialog.alert({
          message: '你没有选择商品哦'
        }).then(() => {})
        return
      }
      this.sid = JSON.stringify(this.sid)
      const obj = this.sid
      const ischeaks = false
      // 根据是否编辑状态来确实用户是删除还是提交订单
      if (this.isEdit) {
        this.remove()
        //  确定删除
      } else {
        this.$router.push({ name: 'Tijiao', query: { obj, ischeaks } })
      }
    },
    // 单选
    checka (value) {
      const cheak = this.resultdata.every(v => {
        return v.ischeak === true
      })
      this.isAll = cheak
      this.sum()
    },
    // 全选
    allCheck () {
      const isAll = this.isAll
      this.resultdata.forEach(v => {
        v.ischeak = isAll
      })
      this.sum()
    },
    // 总价格
    sum () {
      this.price = 0
      this.resultdata.forEach(v => {
        if (v.ischeak) {
          this.price += v.count * v.price * 100
        }
      })
    },
    // 改变数值
    changes (value) {
      this.resetshop(value)
      this.sum()
    },
    // 查询购物车商品
    async eachshop () {
      const tokenString = getToken()
      if (!tokenString) return (this.flag = true)
      const res = await findAllShopcartAPI({
        appkey: this.$store.state.appkey,
        tokenString
      })
      if (res.code === 5000) {
        for (let i = 0; i < res.result.length; i++) {
          res.result[i].ischeak = false
        }
        this.resultdata = res.result
      }
    },
    // 编辑更新购物车
    async resetshop (value) {
      const tokenString = getToken()
      if (!tokenString) return
      const data = {
        // 获取选择的规格
        appkey: this.$store.state.appkey,
        tokenString,
        count: value.count,
        sid: value.sid
      }
      const res = await modifyShopcartCountAPI(data) // 调用编辑购物车接口
      // 修改数量后进行提示
      if (res.code === 6000) {
        this.$toast(res.msg)
      }
    },
    // 删除
    async remove () {
      const tokenString = getToken()
      if (!tokenString) return
      const data = {
        appkey: this.$store.state.appkey,
        tokenString,
        sids: this.sid
      }
      const res = await removeShopcartAPI(data) // 调用删除商品接口
      // 删除购物车商品后提示用户并重新渲染商品和计算价格
      if (res.code === 7000) {
        this.$toast(res.msg) // 提醒用户
        this.eachshop() // 删除后重新调用查询购物车接口
        this.sum() // 重新计算价格
      }
    },
    // 去登录
    goLOgin () {
      this.$router.push({ name: 'Login' })
    },
    // 去菜单
    gocaidan () {
      this.$router.push({ name: 'Caidan' })
    }
  }
}
</script>

<style lang="less" scoped></style>
